﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.XtraCharts;
using NotAClue;
using NotAClue.Web;
using System.Data;
using DevExpress.Web.ASPxPivotGrid;

namespace DD_Extensions.Reports
{
    public partial class oalp : System.Web.UI.Page
    {
        protected void Page_Init(object sender, EventArgs e)
        {
            //ScriptManager sm = ScriptManager.GetCurrent(this);
            //sm.AsyncPostBackTimeout = 36000;
            
            var reportName = Page.RouteData.Values["ReportName"] as String;
            using (var OC = new Models.DD_ExtensionsEntities())
            {
                // get report
                var report = OC.Reports.FirstOrDefault(r => r.Name == reportName);

                // if report is not null then run the report
                if (report == null)
                    throw new InvalidOperationException(String.Format("'{0}' report does not exist.", reportName));

                ReportTitleLabel.Text = String.IsNullOrEmpty(report.DisplayName) ? report.Name : report.DisplayName;

                // setup the data source
                SqlDataSource1.ConnectionString = report.Connection.ConnectionString;
                SqlDataSource1.ProviderName = report.Connection.ProviderName;
                SqlDataSource1.SelectCommand = report.TSQL;

                switch (report.SqlType.ToEnum<Models.SqlType>())
                {
                    case DD_Extensions.Models.SqlType.SPROC:
                        SqlDataSource1.SelectCommandType = SqlDataSourceCommandType.StoredProcedure;
                        foreach (var p in report.SprocParameters)
                        {
                            var param = new Parameter()
                                {
                                    Name = p.Name,
                                    DbType = p.DataType.AsEnum<SqlDbType>().ToDbType(),
                                    ConvertEmptyStringToNull = true,
                                    DefaultValue = p.GetSqlParameterValue()
                                };
                            SqlDataSource1.SelectParameters.Add(param);
                        }
                        break;
                    case DD_Extensions.Models.SqlType.TSQL:
                        SqlDataSource1.SelectCommandType = SqlDataSourceCommandType.Text;
                        break;
                }

                // setup columns
                foreach (var column in report.Columns)
                {
                    //<dx:PivotGridField 
                    //    ID="fieldInvoiceDate" 
                    //    FieldName="InvoiceDate" 
                    //    Area="ColumnArea" 
                    //    AreaIndex="0" 
                    //    Caption="InvoiceYear" 
                    //    GroupInterval="DateYear" 
                    //    UnboundFieldName="fieldInvoiceDate">
                    //</dx:PivotGridField>

                    //<dx:PivotGridField 
                    //    ID="fieldInvoiceDate1" 
                    //    Area="ColumnArea" 
                    //    AreaIndex="1" 
                    //    Caption="InvoiceQuater" 
                    //    GroupInterval="DateQuarter" 
                    //    UnboundFieldName="field1" 
                    //    FieldName="InvoiceDate">
                    //</dx:PivotGridField>

                    //<dx:PivotGridField 
                    //    ID="fieldInvoiceDate2" 
                    //    Visible="False" 
                    //    Area="RowArea" 
                    //    AreaIndex="0" 
                    //    Caption="InvoiceMonth" 
                    //    GroupInterval="DateMonth" 
                    //    ValueFormat-FormatString="MMM" 
                    //    ValueFormat-FormatType="DateTime" 
                    //    UnboundFieldName="field2" 
                    //    FieldName="InvoiceDate">
                    var field = new PivotGridField()
                        {
                            ID = "field" + column.Name,
                            FieldName = column.FieldName,
                            Caption = column.Caption,
                            Area = column.Area.AsEnum<DevExpress.XtraPivotGrid.PivotArea>(),
                            AreaIndex = column.AreaIndex,
                            Visible = column.Visible
                        };

                    if (column.Name != column.FieldName)
                        field.UnboundFieldName = String.Format("Unbound{0}{1}", column.Name, column.FieldName);

                    //var valueFormat = new DevExpress.Utils.FormatInfo();
                    //valueFormat.FormatType = column.FormatType.AsEnum<DevExpress.Utils.FormatType>();

                    //if (!String.IsNullOrEmpty(column.FormatString))
                    //    valueFormat.FormatString = column.FormatString;

                    field.ValueFormat.FormatType = column.FormatType.AsEnum<DevExpress.Utils.FormatType>();

                    if (!String.IsNullOrEmpty(column.FormatString))
                        field.ValueFormat.FormatString = column.FormatString;

                    if (column.GroupInterval.HasValue)
                        field.GroupInterval = ((int)column.GroupInterval).AsEnum<DevExpress.XtraPivotGrid.PivotGroupInterval>();

                    ASPxPivotGrid1.Fields.AddField(field);
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            // turn off hidden filters still working
            ASPxPivotGrid1.OptionsData.FilterByVisibleFieldsOnly = true;

            if (!IsPostBack)
            {
                ShowHideFieldsButton.Text = " » ";
                ShowHideFieldsButton.ToolTip = "Show Fields";
                ASPxPivotCustomizationControl1.Visible = false;
                ASPxPivotGrid1.Width = Global.ASPxPivotGrid1Width + Global.FieldWidth;
                Row1.Visible = false;
                Row2.Visible = false;
                var restrictedTypes = new ViewType[] 
                {
                    ViewType.PolarArea, 
                    ViewType.PolarLine, 
                    ViewType.SideBySideGantt, 
                    ViewType.SideBySideRangeBar,
                    ViewType.RangeBar,
                    ViewType.Gantt,
                    ViewType.PolarPoint,
                    ViewType.Stock,
                    ViewType.CandleStick,
                    ViewType.Bubble
                };

                foreach (ViewType type in Enum.GetValues(typeof(ViewType)))
                {
                    if (Array.IndexOf<ViewType>(restrictedTypes, type) >= 0)
                        continue;

                    ChartType.Items.Add(type.ToString());
                }

                ChartType.SelectedItem = ChartType.Items.FindByText(ViewType.Line.ToString());
                SetChartType(ChartType.SelectedItem.Text);

                //var StaffingSupplierSiteGUIDList = new Parameter("StaffingSupplierSiteGUIDList", System.Data.DbType.String, "3E8F3DCA-0DA5-DD11-B5E9-0021F6000000,787973DE-0DA5-DD11-B5E9-0021F6000000,297AE892-0DA5-DD11-B5E9-0021F6000000");
                //<asp:Parameter DefaultValue="@StaffingSupplierSiteGUIDList='3E8F3DCA-0DA5-DD11-B5E9-0021F6000000,787973DE-0DA5-DD11-B5E9-0021F6000000,297AE892-0DA5-DD11-B5E9-0021F6000000'" Name="StaffingSupplierSiteGUIDList" Type="String" />
                //<asp:Parameter DefaultValue="'01/01/2011'" Name="StartDate" Type="DateTime" />
                //<asp:Parameter DefaultValue="'5/30/12'" Name="EndDate" Type="DateTime" />
                //<asp:Parameter DefaultValue="'Affiliate'" Name="ViewLevel" Type="String" />
                //<asp:Parameter DefaultValue="0" Name="RollUpToParentCustomer" Type="Boolean" />
                //<asp:Parameter DefaultValue="'AccountingPeriodDate'" Name="DateType" Type="String" />

            }
        }

        protected void SetChartType(String text)
        {
            WebChartControl1.SeriesTemplate.ChangeView(text.ToEnum<ViewType>());
        }

        protected void ChartType_ValueChanged(object sender, EventArgs e)
        {
            SetChartType(ChartType.SelectedItem.Text);
        }

        protected override void OnPreRenderComplete(EventArgs e)
        {
            base.OnPreRenderComplete(e);

            if (!IsPostBack)
                ASPxPivotGrid1.LoadUserSetting();
        }

        protected void ShowHideFieldsButton_Click(object sender, EventArgs e)
        {
            if (!ASPxPivotCustomizationControl1.Visible)
            {
                ShowHideFieldsButton.Text = " « ";
                ShowHideFieldsButton.ToolTip = "Hide Fields";
                ASPxPivotCustomizationControl1.Visible = true;
                Row1.Visible = true;
                Row2.Visible = true;
                ASPxPivotGrid1.Width = Global.ASPxPivotGrid1Width;
            }
            else
            {
                ShowHideFieldsButton.Text = " » ";
                ShowHideFieldsButton.ToolTip = "Show Fields";
                ASPxPivotCustomizationControl1.Visible = false;
                Row1.Visible = false;
                Row2.Visible = false;
                ASPxPivotGrid1.Width = Global.ASPxPivotGrid1Width + Global.FieldWidth;
            }
        }

        protected void ExportImageButton_Click(object sender, ImageClickEventArgs e)
        {
            var page = Request.Url.Segments[Request.Url.Segments.Length - 1];
            ASPxPivotGridExporter1.ExportCsvToResponse(page.Substring(0, page.LastIndexOf(".")) + ".csv");
        }

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            ASPxPivotGrid1.SaveUserSetting();
        }
    }
}